package cn.edu.hqu.cst.chapter0204.web;

import cn.edu.hqu.cst.chapter0204.domain.Order;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.validation.Valid;
import java.util.logging.Logger;


@Controller
@RequestMapping("/orders")
@SessionAttributes("order")
public class OrderController {
    private static final Logger log = (Logger) LoggerFactory.getLogger(OrderController.class);

    public OrderController() {
    }

    @GetMapping({"/current"})
    public String orderForm(Model model) {
        model.addAttribute("order", new Order());
        return "orderForm";
    }

    @PostMapping
    public String processOrder(@Valid Order order, Errors errors) {
        if (errors.hasErrors()) {
            return "orderForm";
        } else {
            log.info("Processing order: " + order);
            return "redirect:/design";
        }
    }
}
